
package com.wyzz.hr.bo.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.Map.Entry;

import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.*;

import com.wyzz.hr.base.TreeNode;
import com.wyzz.hr.bo.IDepartmentBO;
import com.wyzz.hr.bo.IDeptHistBo;
import com.wyzz.hr.bo.IEmpHistOrgBo;
import com.wyzz.hr.bo.IEmployeeBo;
import com.wyzz.hr.bo.IOrgheadsBo;
import com.wyzz.hr.bo.IPositionBaseBo;
import com.wyzz.hr.bo.IPositionBo;
import com.wyzz.hr.bo.ISysLogBO;
import com.wyzz.hr.bo.OrgDeptMergeHelper;
import com.wyzz.hr.bo.OrgDeptOperateHelper;
import com.wyzz.hr.dao.IDepartmentDAO;
import com.wyzz.hr.pojo.Department;
import com.wyzz.hr.pojo.Depthist;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Emptransfer;
import com.wyzz.hr.pojo.Orgheads;
import com.wyzz.hr.pojo.Position;
import com.wyzz.hr.pojo.PositionBase;
import com.wyzz.hr.pojo.PositionBaseHist;
import com.wyzz.hr.pojo.Userinfo;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.DateUtil;
import com.wyzz.hr.util.Message;
import com.wyzz.hr.util.ObjectUtil;
import com.wyzz.hr.util.StringUtil;


public class DepartmentBOImpl implements IDepartmentBO {

	public DepartmentBOImpl() {
		dao = null;
		helper = new OrgDeptOperateHelper();
	}

	public List FindAllDepartment() {
		DetachedCriteria dc = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Department.class);
		dc.addOrder(Order.asc("departmentSortId"));
		List deptList = dao.findByCriteria(dc);
		return deptList;
	}

	public List FindEnabledDepartment() {
		DetachedCriteria dc = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Department.class);
		dc.add(Restrictions.eq(Department.PROP_DEPARTMENT_STATUS,
				new Integer(1)));
		dc.addOrder(Order.asc("departmentSortId"));
		return dao.findByCriteria(dc);
	}

	public List getSubDeptsByParentId(String parentId) {
		DetachedCriteria dc = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Department.class);
		dc.createAlias(Department.PROP_DEPARTMENT_PARENT_ID,
				"departmentParentId", 1);
		dc.add(Restrictions.eq(Department.PROP_DEPARTMENT_STATUS,
				new Integer(1)));
		dc.add(Restrictions.eq(Department.PROP_DEPARTMENT_PARENT_ID,
				new Department(parentId)));
		dc.addOrder(Order.asc("departmentSortId"));
		return dao.findByCriteria(dc);
	}

	public synchronized Integer getMaxSortId() {
		String hql = "select max(departmentSortId) as maxSortId from Department dept";
		List maxNoList = dao.exeHqlList(hql);
		Integer maxID;
		if (maxNoList == null || maxNoList.size() < 1
				|| maxNoList.get(0) == null)
			maxID = Integer.valueOf(1);
		else
			maxID = Integer.valueOf(1 + ((Integer) (Integer) maxNoList.get(0))
					.intValue());
		return maxID;
	}

	public boolean addDeptSave(Department dept, PositionBase respPB,
			Position pos, Depthist deptHist, PositionBaseHist respPBHist) {
		String msgNewDept = "\u65B0\u5EFA\u90E8\u95E8{0}\u3002";
		String msgNewPB = "\u65B0\u5EFA\u804C\u4F4D{0}\u3002";
		HttpSession session = ServletActionContext.getRequest().getSession();
		Employee currentEmp = ((Userinfo) session.getAttribute("userinfo"))
				.getEmployee();
		dao.saveObject(dept);
		dao.saveObject(deptHist);
		ISysLogBO logBO = (ISysLogBO) SpringBeanFactory.getBean("logBO");
		String msg = StringUtil.message(msgNewDept, new Object[] { dept
				.getDepartmentName() });
		logBO.addToSyslog("department", currentEmp.getId(), null, dept.getId(),
				0, "\u65B0\u5EFA", msg);
		dao.saveObject(respPB);
		dao.saveObject(respPBHist);
		dao.saveObject(pos);
		msg = StringUtil.message(msgNewPB, new Object[] { respPB.getPbName() });
		logBO.addToSyslog("positionbase", currentEmp.getId(), null, respPB
				.getId(), 0, "\u65B0\u5EFA", msg);
		return true;
	}

	public String saveProcessDeptRename(Department dept) {
		helper.operateDeptRename(dept);
		return "SUCC";
	}

	public String saveDeptMove(String fromId, String toId) {
		Department fromDept = getDeptById(fromId);
		Department toDept = getDeptById(toId);
		helper.operateDeptMove(fromDept, toDept);
		return "SUCC";
	}

	public void saveMergeDept(String fromIds, String toId,
			String fromPBInfo[][], Message msg) {
		String info = msg.getMsgContent();
		List fromDeptList = new ArrayList();
		String fromIdArray[] = fromIds.split(",");
		for (int i = 0; i < fromIdArray.length; i++) {
			Department dept = getDeptById(fromIdArray[i]);
			fromDeptList.add(dept);
		}

		Department toDept = getDeptById(toId);
		for (Iterator i$ = fromDeptList.iterator(); i$.hasNext();) {
			Department fromDept = (Department) i$.next();
			OrgDeptMergeHelper operateHelper = new OrgDeptMergeHelper(fromDept,
					toDept);
			IPositionBo posBo = (IPositionBo) SpringBeanFactory
					.getBean("positionBo");
			String respPosId = posBo.getRespPosOfDept(fromDept.getId()).getId();
			for (int i = 0; fromPBInfo != null && i < fromPBInfo.length; i++) {
				if (!fromPBInfo[i][5].equals(fromDept.getId()))
					continue;
				String pbId = fromPBInfo[i][0];
				String pbInCharge = fromPBInfo[i][1];
				String operate = fromPBInfo[i][2];
				String toPBId = fromPBInfo[i][3];
				String canelResp = fromPBInfo[i][4];
				if ("1".equals(pbInCharge) && "1".equals(operate)) {
					String tempInfo = operateHelper.respPBCopy(pbId);
					if (!"SUCC".equals(tempInfo)) {
						info = (new StringBuilder()).append(info).append(
								tempInfo).toString();
						break;
					}
				}
				if ("1".equals(pbInCharge) && "2".equals(operate)) {
					String tempInfo = operateHelper.respPBMoveTo(pbId, toPBId);
					if (!"SUCC".equals(tempInfo)) {
						info = (new StringBuilder()).append(info).append(
								tempInfo).toString();
						break;
					}
				}
				if ("0".equals(pbInCharge) && "1".equals(operate)) {
					String tempInfo = operateHelper.pbCopy(pbId);
					if (!"SUCC".equals(tempInfo)) {
						info = (new StringBuilder()).append(info).append(
								tempInfo).toString();
						break;
					}
				}
				if ("0".equals(pbInCharge) && "2".equals(operate)) {
					String tempInfo = operateHelper.pbMoveTo(pbId, toPBId);
					if (!"SUCC".equals(tempInfo)) {
						info = (new StringBuilder()).append(info).append(
								tempInfo).toString();
						break;
					}
				}
				if ("1".equals(pbInCharge) && "1".equals(canelResp))
					operateHelper.cancelResp(respPosId);
			}

			if ("SUCC".equals(info)) {
				String tempInfo = operateHelper.deptOperate();
				if (!"SUCC".equals(tempInfo))
					info = (new StringBuilder()).append(info).append(tempInfo)
							.toString();
			}
			msg.setMsgContent(info);
			if (!"SUCC".equals(info)) {
				msg.setMsgContent(info.replace("SUCC", ""));
				throw new RuntimeException();
			}
		}

	}

	/**
	 * @deprecated Method FindAllDepartmentConHead is deprecated
	 */

	public List FindAllDepartmentConHead() {
		DetachedCriteria dc = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Department.class);
		dc.addOrder(Order.asc("departmentSortId"));
		List result = dao.findByCriteria(dc);
		Department temp = new Department();
		Boolean flag = Boolean.valueOf(false);
		IEmployeeBo empBo = (IEmployeeBo) SpringBeanFactory.getBean("empBo");
		IOrgheadsBo headsBo = (IOrgheadsBo) SpringBeanFactory
				.getBean("headsBo");
		List orgheadlist = headsBo.listOrgheadNo("deptheader");
		List orgheadempIdlist = new ArrayList();
		Orgheads orgheadObj;
		for (Iterator i$ = orgheadlist.iterator(); i$.hasNext(); orgheadempIdlist
				.add(orgheadObj.getOrgheadsEmpNo()))
			orgheadObj = (Orgheads) i$.next();

		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		List emplist;
		if (orgheadempIdlist.size() == 0) {
			emplist = null;
		} else {
			detachedCriteria.add(Restrictions.in(Employee.PROP_ID,
					orgheadempIdlist));
			emplist = empBo.findByCriteria(detachedCriteria);
		}
		label0: for (int i = 0; i < (result != null ? result.size() : 0); i++) {
			flag = Boolean.valueOf(false);
			int j = 0;
			do {
				if (j >= (orgheadlist != null ? orgheadlist.size() : 0))
					continue label0;
				if (((Department) result.get(i)).getId().equals(
						((Orgheads) orgheadlist.get(j)).getOrgheadsOrgNo())) {
					int k = 0;
					do {
						if (k >= (emplist != null ? emplist.size() : 0))
							break;
						if (((Orgheads) orgheadlist.get(j)).getOrgheadsEmpNo()
								.equals(((Employee) emplist.get(k)).getId())) {
							temp = (Department) result.get(i);
							temp.setHeadNo(((Employee) emplist.get(k)).getId());
							temp.setHeadName(((Employee) emplist.get(k))
									.getEmpName());
							result.set(i, temp);
							flag = Boolean.valueOf(true);
							break;
						}
						k++;
					} while (true);
				}
				if (flag.booleanValue())
					continue label0;
				j++;
			} while (true);
		}

		return result;
	}

	public boolean saveorUpdateDepartment(Department dept) {
		try {
			dao.saveOrupdate(dept);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * @deprecated Method addDepartment is deprecated
	 */

	public boolean addDepartment(Department dept) {
		try {
			String trimmedDepartmentName = dept.getDepartmentName().trim();
			List old = dao.exeHqlList((new StringBuilder()).append(
					" from Department where departmentName ='").append(
					trimmedDepartmentName).append("'").toString());
			if (old == null || old.size() == 0) {
				dept.setDepartmentName(trimmedDepartmentName);
				dao.saveObject(dept);
				if (StringUtils.isNotEmpty(dept.getDeptHeader())) {
					Orgheads head = new Orgheads();
					head.setOrgheadsEmpNo(dept.getDeptHeader());
					head.setOrgheadsOrgNo(dept.getId());
					head.setOrgheadsResponsibility("deptheader");
					dao.saveObject(head);
				}
				return true;
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}

	/**
	 * @deprecated Method delDepartment is deprecated
	 */

	public String delDepartment(Class name, String id) {
		StringBuffer message = new StringBuffer();
		try {
			List check = null;
			check = dao.exeHqlList((new StringBuilder()).append(
					"select count(*) from Empsalarypay where espDept = '")
					.append(id).append("'").toString());
			if (Integer.valueOf(check.get(0).toString()).intValue() > 0)
				message
						.append("\u6709\u6BCF\u6708\u85AA\u8D44\u53D1\u653E\u6570\u636E\u5173\u8054\u5230\u8BE5\u90E8\u95E8\uFF01");
			check = dao.exeHqlList((new StringBuilder()).append(
					"select count(*) from Employee where empDeptNo = '")
					.append(id).append("'").toString());
			if (Integer.valueOf(check.get(0).toString()).intValue() > 0)
				message
						.append("\u8BE5\u90E8\u95E8\u4E0B\u6709\u5458\u5DE5\u5B58\u5728\uFF01");
			check = dao
					.exeHqlList((new StringBuilder())
							.append(
									"select count(*) from Businessunit where businessunitDeptNo = '")
							.append(id).append("'").toString());
			if (Integer.valueOf(check.get(0).toString()).intValue() > 0)
				message
						.append("\u8BE5\u90E8\u95E8\u4E0B\u6709\u4E1A\u52A1\u5355\u5143\u5B58\u5728\uFF01");
			Department department = (Department) dao.loadObject(name, id, null,
					new boolean[0]);
			if (message.toString().length() == 0) {
				dao.deleteObject(department);
				dao.exeHql((new StringBuilder()).append(
						"delete from Orgheads where orgheads_org_no='").append(
						id).append("'").toString());
			}
		} catch (Exception e) {
			message.append((new StringBuilder()).append(
					"\u7CFB\u7EDF\u5F02\u5E38\uFF1A").append(e.getMessage())
					.toString());
		}
		return message.toString();
	}

	/**
	 * @deprecated Method updateDepartment is deprecated
	 */

	public String updateDepartment(Department dept) {
		String trimmedDepartmentName = dept.getDepartmentName().trim();
		if (dept.getDepartmentStatus().intValue() == 0) {
			List check = new ArrayList();
			check = dao.exeHqlList((new StringBuilder()).append(
					"select count(*) from Employee where empDeptNo = '")
					.append(dept.getId()).append("'").toString());
			if (Integer.valueOf(check.get(0).toString()).intValue() > 0)
				return "error1";
			check = dao
					.exeHqlList((new StringBuilder())
							.append(
									"select count(*) from Businessunit where businessunitDeptNo = '")
							.append(dept.getId()).append("'").toString());
			if (Integer.valueOf(check.get(0).toString()).intValue() > 0)
				return "error2";
		}
		List old = dao.exeHqlList((new StringBuilder()).append(
				" from Department where  id != '").append(dept.getId()).append(
				"'  and departmentName  ='").append(trimmedDepartmentName)
				.append("'").toString());
		if (old == null || old.size() == 0) {
			Department oldDepartment = (Department) dao.loadObject(
					com.wyzz.hr.pojo.Department.class, dept.getId(), null,
					new boolean[0]);
			oldDepartment.setDepartmentDesc(dept.getDepartmentDesc());
			oldDepartment.setDepartmentName(trimmedDepartmentName);
			oldDepartment.setDepartmentStatus(dept.getDepartmentStatus());
			oldDepartment.setDepartmentSortId(dept.getDepartmentSortId());
			dao.updateObject(oldDepartment);
			Orgheads head = new Orgheads();
			IOrgheadsBo headsbo = (IOrgheadsBo) SpringBeanFactory
					.getBean("headsBo");
			if (StringUtils.isNotEmpty(dept.getDeptHeader()))
				if (oldDepartment.getDeptHeader() == null
						|| oldDepartment.getDeptHeader().trim().equals("")) {
					head.setOrgheadsEmpNo(dept.getDeptHeader());
					head.setOrgheadsOrgNo(oldDepartment.getId());
					head.setOrgheadsResponsibility("deptheader");
					headsbo.insert(head);
				} else if (!dept.getDeptHeader().trim().equalsIgnoreCase(
						oldDepartment.getDeptHeader().trim())) {
					String hql = (new StringBuilder()).append(
							"delete from Orgheads where orgheadsEmpNo='")
							.append(dept.getDeptHeader()).append(
									"' and orgheadsOrgNo='").append(
									dept.getId()).append("'").toString();
					dao.exeHql(hql);
					String hql2 = (new StringBuilder())
							.append(
									"delete from Orgheads where orgheadsOrgNo='")
							.append(dept.getId())
							.append("' and orgheadsResponsibility='deptheader'")
							.toString();
					dao.equals(hql2);
					head.setOrgheadsEmpNo(dept.getDeptHeader());
					head.setOrgheadsOrgNo(oldDepartment.getId());
					head.setOrgheadsResponsibility("deptheader");
					headsbo.insert(head);
				}
			return "success";
		} else {
			return "exist";
		}
	}

	/**
	 * @deprecated Method getDepartmentsByNos is deprecated
	 */

	public List getDepartmentsByNos(String deptNos[]) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Department.class);
		detachedCriteria.add(Restrictions.in(Department.PROP_ID, deptNos));
		return dao.findByCriteria(detachedCriteria);
	}

	public Department getDeptById(String deptId) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Department.class);
		detachedCriteria.createAlias(Department.PROP_DEPARTMENT_PARENT_ID,
				Department.PROP_DEPARTMENT_PARENT_ID, 1);
		detachedCriteria.add(Restrictions.eq(Department.PROP_ID, deptId));
		List deptList = dao.findByCriteria(detachedCriteria);
		if (deptList.size() > 0)
			return (Department) deptList.get(0);
		else
			return null;
	}

	public Department getDeptByName(String deptName, String parentId) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Department.class);
		detachedCriteria.createAlias(Department.PROP_DEPARTMENT_PARENT_ID,
				Department.PROP_DEPARTMENT_PARENT_ID, 1);
		detachedCriteria.add(Restrictions.eq(Department.PROP_DEPARTMENT_NAME,
				deptName));
		detachedCriteria.add(Restrictions.eq((new StringBuilder()).append(
				Department.PROP_DEPARTMENT_PARENT_ID).append(".id").toString(),
				parentId));
		List deptList = dao.findByCriteria(detachedCriteria);
		if (deptList.size() > 0)
			return (Department) deptList.get(0);
		else
			return null;
	}

	public Department loadDepartmentByNo(String deptNo, String fetch[]) {
		return (Department) dao.loadObject(com.wyzz.hr.pojo.Department.class,
				deptNo, fetch, new boolean[0]);
	}

	/**
	 * @deprecated Method saveDepartmentSortIdByBatch is deprecated
	 */

	public void saveDepartmentSortIdByBatch(String ids[]) {
		int length = ids.length;
		int sortId = 1;
		for (int i = 0; i < length; i++) {
			dao.exeHql((new StringBuilder()).append(
					"update Department set departmentSortId=").append(sortId)
					.append(" where id ='").append(ids[i]).append("'")
					.toString());
			sortId++;
		}

	}

	public int getActiveEmpNos(String deptId) {
		List subDepts = getAllSubDeptsOfDept(new Department(deptId));
		DetachedCriteria dc = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		dc.add(Restrictions.eq(Employee.PROP_EMP_STATUS, new Integer(1)));
		dc.add(Restrictions.in(Employee.PROP_EMP_DEPT_NO, subDepts));
		return dao.findRowCountByCriteria(dc);
	}

	public int getOrderEmpNos(String deptId) {
		List deptIdList = getAllSubDepts(new Integer(1),
				new String[] { deptId });
		String deptIdStr = "";
		for (int i = 0; deptIdList != null && i < deptIdList.size(); i++)
			deptIdStr = (new StringBuilder()).append(deptIdStr).append("'")
					.append(((Department) deptIdList.get(i)).getId()).append(
							"',").toString();

		String hql = (new StringBuilder())
				.append(
						"select sum(pbMaxEmployee) from PositionBase where pbDeptId.id in (")
				.append(deptIdStr.substring(0, deptIdStr.length() - 1)).append(
						") and pbStatus=1").toString();
		List list = dao.exeHqlList(hql);
		if (list != null && list.size() > 0 && list.get(0) != null
				&& !"".equals(list.get(0))) {
			Long num = (Long) (Long) list.get(0);
			return num.intValue();
		} else {
			return 0;
		}
	}

	public void update_disableDept(String deptId, Message msg) {
		String info = helper.operateDisableDept(deptId);
		if (!info.equals("SUCC")) {
			msg.setMsgContent(info);
			throw new RuntimeException();
		} else {
			return;
		}
	}

	public String update_enableDept(String deptId) {
		String info = "SUCC";
		Department currentDept = getDeptById(deptId);
		IPositionBaseBo pbBo = (IPositionBaseBo) SpringBeanFactory
				.getBean("positionBaseBo");
		List pbList = pbBo.getAllPbsOfDept(new String[] { deptId });
		for (int i = 0; i < pbList.size(); i++) {
			PositionBase pb = (PositionBase) pbList.get(i);
			String tempInfo = helper.operateEnablePB(pb);
			if (!tempInfo.equals("SUCC"))
				info = (new StringBuilder()).append(info).append(tempInfo)
						.toString();
		}

		helper.operateEnableCurrentDept(currentDept);
		return info;
	}

	public void deleteDept(String deptId, Message msg) {
		String info = helper.operateDeleteDept(deptId);
		if (!info.equals("SUCC")) {
			msg.setMsgContent(info);
			throw new RuntimeException();
		} else {
			return;
		}
	}

	public String getDeptInCharge(String posId) {
		IPositionBo posBo = (IPositionBo) SpringBeanFactory
				.getBean("positionBo");
		Position position = posBo.getPosById(posId,
				new String[] { Position.PROP_POSITION_PB_ID });
		if (position.getPositionPbId().getPbInCharge().intValue() == 1)
			return position.getPositionPbId().getPbDeptId().getId();
		else
			return null;
	}

	public String[] getAllSubDeptIds(int sign, String deptNo) {
		List subDeptList = getAllSubDepts(new Integer(1),
				new String[] { deptNo });
		if (subDeptList == null)
			return null;
		if (sign == 0)
			subDeptList.remove(0);
		List subDeptNoList = new ArrayList();
		Department tempDept;
		for (Iterator i$ = subDeptList.iterator(); i$.hasNext(); subDeptNoList
				.add(tempDept.getId()))
			tempDept = (Department) i$.next();

		if (subDeptNoList.size() == 0)
			return null;
		else
			return (String[]) subDeptNoList.toArray(new String[subDeptNoList
					.size()]);
	}

	public String[] getAllSubDeptIds(String deptNos[]) {
		List subDeptList = getAllSubDepts(new Integer(1), deptNos);
		if (subDeptList == null)
			return null;
		List subDeptNoList = new ArrayList();
		Department tempDept;
		for (Iterator i$ = subDeptList.iterator(); i$.hasNext(); subDeptNoList
				.add(tempDept.getId()))
			tempDept = (Department) i$.next();

		return (String[]) subDeptNoList
				.toArray(new String[subDeptNoList.size()]);
	}

	public List getAllSubDepts(Integer status, String deptNos[]) {
		DetachedCriteria dc = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Department.class);
		if (status != null)
			dc.add(Restrictions.eq(Department.PROP_DEPARTMENT_STATUS, status));
		List allDeptList = dao.findByCriteria(dc);
		Iterator iter = allDeptList.iterator();
		List subDeptQueue = new ArrayList();
		do {
			if (!iter.hasNext())
				break;
			Department tempDept = (Department) iter.next();
			if (ObjectUtil.contains(deptNos, tempDept.getId())) {
				subDeptQueue.add(tempDept);
				iter.remove();
			}
		} while (true);
		if (subDeptQueue.size() == 0)
			return null;
		Department parentDept = null;
		label0: for (int i = 0; i < subDeptQueue.size(); i++) {
			parentDept = (Department) subDeptQueue.get(i);
			Iterator iterTemp = allDeptList.iterator();
			do {
				if (!iterTemp.hasNext())
					continue label0;
				Department tempDept = (Department) iterTemp.next();
				if (tempDept.getDepartmentParentId() != null
						&& tempDept.getDepartmentParentId().getId().equals(
								parentDept.getId())) {
					subDeptQueue.add(tempDept);
					iterTemp.remove();
				}
			} while (true);
		}

		return subDeptQueue;
	}

	public Map getSubDeptsOfDeptandDirectSub(Department dept) {
		Map map = new HashMap();
		if (dept == null || StringUtils.isEmpty(dept.getId()))
			return map;
		List allSubDeptList = getAllSubDepts(null,
				new String[] { dept.getId() });
		if (allSubDeptList == null || allSubDeptList.size() == 0)
			return map;
		List deptList = new ArrayList();
		deptList.add(dept);
		map.put(dept, deptList);
		if (allSubDeptList.size() == 1)
			return map;
		for (int i = 1; i < allSubDeptList.size(); i++) {
			Department tempDept;
			Department directSubDept;
			label0: {
				tempDept = (Department) allSubDeptList.get(i);
				Department parent = tempDept.getDepartmentParentId();
				if (parent.equals(dept)) {
					if (!map.containsKey(tempDept)) {
						List tempDeptList = new ArrayList();
						tempDeptList.add(tempDept);
						map.put(tempDept, tempDeptList);
					}
					continue;
				}
				directSubDept = tempDept;
				do {
					if (directSubDept.getDepartmentParentId().equals(dept))
						break label0;
					int j = 1;
					do {
						if (j < allSubDeptList.size()) {
							label1: {
								Department tempSubDept = (Department) allSubDeptList
										.get(j);
								if (!tempSubDept.equals(directSubDept
										.getDepartmentParentId()))
									break label1;
								directSubDept = tempSubDept;
							}
						}
						if (true)
							break;
						j++;
					} while (true);
				} while (true);
			}
			if (directSubDept == null)
				continue;
			List tempDeptList = (List) map.get(directSubDept);
			if (tempDeptList == null) {
				tempDeptList = new ArrayList();
				tempDeptList.add(directSubDept);
				map.put(directSubDept, tempDeptList);
			}
			tempDeptList.add(tempDept);
		}

		return map;
	}

	public List getAllSubDeptsOfDept(Department dept) {
		DetachedCriteria dc = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Department.class);
		List allDeptList = dao.findByCriteria(dc);
		List subDeptList = new ArrayList();
		int i = 0;
		do {
			if (allDeptList == null || i >= allDeptList.size())
				break;
			Department tempDept = (Department) allDeptList.get(i);
			if (tempDept.getId().equals(dept.getId())) {
				subDeptList.add(tempDept);
				break;
			}
			i++;
		} while (true);
		Iterator iter = allDeptList.iterator();
		label0: for (i = 0; subDeptList != null && i < subDeptList.size(); i++) {
			Department parentDept = (Department) subDeptList.get(i);
			do {
				if (!iter.hasNext())
					continue label0;
				Department tempDept = (Department) iter.next();
				if (tempDept != null
						&& tempDept.getDepartmentParentId() != null
						&& parentDept != null
						&& tempDept.getDepartmentParentId().getId().equals(
								parentDept.getId())) {
					subDeptList.add(tempDept);
					iter.remove();
				}
			} while (true);
		}

		return subDeptList;
	}

	public boolean saveEmpTransferData(Employee emp, Department newDept,
			PositionBase newPB) {
		if (newDept == null && newPB == null)
			return true;
		IEmpHistOrgBo emphistorgBo = (IEmpHistOrgBo) SpringBeanFactory
				.getBean("empHistOrgBo");
		Emptransfer transfer = null;
		transfer = gernerateTransfer(emp, newDept, newPB);
		if (newDept != null)
			emp.setEmpDeptNo(newDept);
		if (newPB != null)
			emp.setEmpPbNo(newPB);
		emphistorgBo.saveEmpHistOrg(emp, newDept, newPB);
		dao.saveOrupdate(emp);
		dao.saveOrupdate(transfer);
		return true;
	}

	private Emptransfer gernerateTransfer(Employee emp, Department newDept,
			PositionBase newPB) {
		OrgDeptOperateHelper helper = new OrgDeptOperateHelper();
		Employee currentEmployee = helper.getCurrentEmp();
		Emptransfer obj = new Emptransfer();
		obj.setEmployee(emp);
		obj.setEftTransferDate(new Date());
		obj.setEftTransferType("0");
		if (newDept != null) {
			obj.setEftOldDeptNo(emp.getEmpDeptNo());
			obj.setEftNewDeptNo(newDept);
		}
		if (newPB != null) {
			obj.setEftOldPbId(emp.getEmpPbNo());
			obj.setEftNewPbId(newPB);
		}
		obj.setEftReason("\u90E8\u95E8\u5408\u5E76");
		obj.setEftCreateDate(new Date());
		obj.setEftCreateBy(currentEmployee.getId());
		obj.setEftLastChangeBy(currentEmployee.getId());
		obj.setEftLastChangeTime(new Date());
		obj.setEftComments("\u90E8\u95E8\u5408\u5E76");
		return obj;
	}

	public List FindEnabledDepartmentNode() {
		List nodeList = new ArrayList();
		List deptList = FindEnabledDepartment();
		Department dept;
		for (Iterator i$ = deptList.iterator(); i$.hasNext(); nodeList
				.add(new TreeNode(dept.getId(), dept.getDepartmentName(), dept
						.getDepartmentParentId().getId(), dept
						.getDepartmentCate().intValue()))) {
			dept = (Department) i$.next();
			if (dept.getDepartmentParentId() == null)
				dept.setDepartmentParentId(new Department("0"));
		}

		return nodeList;
	}

	public List getAllActiveDeptEmpNumList() {
		DetachedCriteria dc = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		dc.createAlias(Employee.PROP_EMP_DEPT_NO, "dept");
		dc.add(Restrictions.eq(Employee.PROP_EMP_STATUS, new Integer(1)));
		dc.setProjection(Projections.projectionList().add(
				Projections.rowCount()).add(
				Projections.groupProperty((new StringBuilder()).append("dept.")
						.append(Department.PROP_ID).toString())));
		return dao.findByProjectionDetachedCriteria(dc);
	}

	public Map getDeptLevels(Department deptArray[], Date date) {
		if (deptArray == null || deptArray.length < 1)
			return null;
		List allActiveDepts = new ArrayList();
		if (date == null) {
			allActiveDepts = FindEnabledDepartment();
		} else {
			IDeptHistBo deptHistBo = (IDeptHistBo) SpringBeanFactory
					.getBean("deptHistBo");
			List dhList = deptHistBo.getDhsBeforeQueryDate(date);
			for (int i = 0; i < dhList.size(); i++) {
				Depthist dh = (Depthist) dhList.get(i);
				allActiveDepts.add(dh.assembleDeptByDh());
			}

		}
		Map deptLevelsMap = new HashMap();
		for (int i = 0; i < deptArray.length; i++) {
			Department dept = deptArray[i];
			if (dept == null)
				continue;
			String deptKey = dept.getId();
			if (deptLevelsMap.containsKey(deptKey))
				continue;
			List superList = superDeptListOfDept(dept, allActiveDepts);
			Department superLevels[] = new Department[4];
			for (int j = 0; j < superList.size(); j++)
				if (j == 0) {
					Department superDept = (Department) superList.get(j);
					if (superDept.getDepartmentCate() != null
							&& superDept.getDepartmentCate().equals(
									Integer.valueOf(1)))
						superLevels[0] = superDept;
					superLevels[1] = superDept;
				} else {
					Department superDept = (Department) superList.get(j);
					superLevels[j + 1] = superDept;
				}

			deptLevelsMap.put(deptKey, superLevels);
		}

		return deptLevelsMap;
	}

	private List superDeptListOfDept(Department dept, List allActiveDepts) {
		List superList = new ArrayList();
		superList.add(dept);
		if (dept.getDepartmentParentId() == null
				|| dept.getDepartmentParentId().getId().equals("rootid"))
			return superList;
		String turnDeptId = dept.getDepartmentParentId().getId();
		boolean turnIdExist;
		label0: do {
			turnIdExist = false;
			Iterator i$ = allActiveDepts.iterator();
			Department deptInWhile;
			do {
				if (!i$.hasNext())
					continue label0;
				deptInWhile = (Department) i$.next();
			} while (!deptInWhile.getId().equals(turnDeptId));
			turnIdExist = true;
			superList.add(deptInWhile);
			if (deptInWhile.getDepartmentParentId() == null)
				turnDeptId = null;
			else
				turnDeptId = deptInWhile.getDepartmentParentId().getId();
		} while (!turnDeptId.equals("rootid") && turnIdExist);
		Collections.reverse(superList);
		if (superList.size() > 3)
			superList = superList.subList(0, 3);
		return superList;
	}

	public void setListDeptLevels(List results, String deptField,
			String branchField, String deptLevelPrefix, String dateField[]) {
		if ((results == null) || (results.size() < 1)) {
			return;
		}
		String dateString = null;
		if ((dateField != null) && (dateField.length == 1))
			dateString = dateField[0];
		if (!StringUtils.isEmpty(dateString)) {
			for (Iterator i$ = results.iterator(); i$.hasNext();) {
				Object obj = i$.next();
				try {
					Department dept = (Department) PropertyUtils
							.getNestedProperty(obj, deptField);
					Date date = null;
					Object dateObj = PropertyUtils.getNestedProperty(obj,
							dateString);
					if (dateObj instanceof String) {
						String dateSourceString = (String) dateObj;
						if (dateSourceString.trim().length() == 6) {
							dateSourceString = dateSourceString.substring(0, 4)
									+ "-" + dateSourceString.substring(4);
							date = DateUtil.parseDateByFormat(dateSourceString,
									"yyyy-MM");
						}
					} else {
						date = (Date) dateObj;
					}
					Map deptLevelsMap = getDeptLevels(
							new Department[] { dept }, date);
					Department[] deptLevels = (Department[]) deptLevelsMap
							.get(dept.getId());
					if (deptLevels != null) {
						PropertyUtils.setNestedProperty(obj, branchField,
								deptLevels[0]);
						int i = 1;
						for (i = 1; i < deptLevels.length; i++) {
							PropertyUtils.setNestedProperty(obj,
									deptLevelPrefix + i, deptLevels[i]);
						}
					}
				} catch (Exception e) {
				}
			}
		} else {
			Department[] deptArray = new Department[results.size()];
			for (int i = 0; i < results.size(); ++i) {
				Department dept;
				try {
					dept = (Department) PropertyUtils.getNestedProperty(results
							.get(i), deptField);
				} catch (Exception e) {
					return;
				}
				deptArray[i] = dept;
			}
			Map deptLevelsMap = getDeptLevels(deptArray, null);
			for (Iterator i$ = results.iterator(); i$.hasNext();) {
				Object obj = i$.next();
				try {
					Department dept = (Department) PropertyUtils
							.getNestedProperty(obj, deptField);
					Department[] deptLevels = (Department[]) deptLevelsMap
							.get(dept.getId());
					if (deptLevels != null) {
						PropertyUtils.setNestedProperty(obj, branchField,
								deptLevels[0]);
						int i = 1;
						for (i = 1; i < deptLevels.length; i++) {
							PropertyUtils.setNestedProperty(obj,
									deptLevelPrefix + i, deptLevels[i]);
						}
					}
				} catch (Exception e) {
				}
			}
		}
	}

	public List setDeptOfNodeList(List nodeList, int status) {
		List depts;
		if (status == 0)
			depts = FindEnabledDepartment();
		else
			depts = FindAllDepartment();
		TreeNode node;
		for (Iterator i$ = depts.iterator(); i$.hasNext(); nodeList.add(node)) {
			Department dept = (Department) i$.next();
			if (dept.getDepartmentParentId() == null)
				dept.setDepartmentParentId(new Department("0"));
			node = null;
			if (status == 0) {
				node = new TreeNode(dept.getId(), dept.getDepartmentName(),
						dept.getDepartmentParentId().getId(), dept
								.getDepartmentCate().intValue());
				continue;
			}
			if (dept.getDepartmentStatus().intValue() == 1)
				node = new TreeNode(dept.getId(), dept.getDepartmentName(),
						dept.getDepartmentParentId().getId(), dept
								.getDepartmentCate().intValue());
			else
				node = new TreeNode(dept.getId(), dept.getDepartmentName(),
						"disable", dept.getDepartmentCate().intValue());
		}

		if (status != 0)
			nodeList.add(new TreeNode("disabled",
					"\u505C\u7528\u7684\u7EC4\u7EC7\u7ED3\u6784", "0", 11));
		return depts;
	}

	public Map getDeptLevelNameMap() {
		Map levelNameMap = new HashMap();
		List deptList = FindEnabledDepartment();
		for (int i = 0; deptList != null && i < deptList.size(); i++) {
			Department dept = (Department) deptList.get(i);
			String levelName = null;
			if (dept.getDepartmentParentId() != null
					&& dept.getDepartmentParentId().getId() != null) {
				levelName = dept.getDepartmentName();
				Department parentDept = dept;
				do {
					parentDept = getDeptById(deptList, parentDept
							.getDepartmentParentId().getId());
					if (parentDept.getDepartmentParentId() == null
							|| parentDept.getDepartmentParentId().getId() == null)
						break;
					levelName = (new StringBuilder()).append(
							parentDept.getDepartmentName()).append("@@")
							.append(levelName).toString();
				} while (true);
			}
			levelNameMap.put((new StringBuilder()).append(dept.getId()).append(
					"@@").append(dept.getDepartmentName()).toString(),
					levelName);
		}

		return levelNameMap;
	}

	/**
	 * @deprecated Method checkInputDeptLevel is deprecated
	 */

	public String checkInputDeptLevel(Map levelNameMap, String inputNameArr[]) {
		Set keySet = levelNameMap.keySet();
		Iterator iter = keySet.iterator();
		int count = 0;
		String lastDeptName = inputNameArr[5];
		String fitKeyValue = null;
		do {
			if (!iter.hasNext())
				break;
			String keyValue = (String) iter.next();
			if (keyValue.indexOf(lastDeptName) >= 0) {
				String levelName = (String) levelNameMap.get(keyValue);
				String levelNameArr[] = levelName.split("@@");
				if (lastDeptName.equals(levelNameArr[levelNameArr.length - 1])) {
					boolean fit = true;
					for (int i = 0; i < inputNameArr.length - 1; i++) {
						String inputNameTemp = inputNameArr[i];
						String levelNameTemp = null;
						if (i < levelNameArr.length - 1)
							levelNameTemp = levelNameArr[i + 1];
						if (inputNameTemp != null && levelNameTemp != null
								&& !inputNameTemp.equals(levelNameTemp))
							fit = false;
						if (inputNameTemp != null && levelNameTemp == null)
							fit = false;
					}

					if (fit) {
						fitKeyValue = keyValue;
						count++;
					}
				}
			}
		} while (true);
		if (count == 0 || count > 1)
			return null;
		else
			return fitKeyValue.split("@@")[0];
	}

	public Integer checkInputDeptLevel(Employee emp, Map levelNameMap) {
		int count;
		boolean deptExist;
		Iterator i$;
		count = 0;
		deptExist = false;
		i$ = levelNameMap.entrySet().iterator();
		boolean deptMatch;
		String deptIdName[] = null;
		do {
			do {
				String levelNameArr[];
				Entry entry = null;
				do {
					if (!i$.hasNext())
						break; /* Loop/switch isn't completed */
					entry = (Entry) i$.next();
					deptIdName = ((String) entry.getKey()).split("@@");
				} while (!deptIdName[1].equals(emp.getEmpDeptNo()
						.getDepartmentName()));
				deptExist = true;
				deptMatch = true;
				levelNameArr = new String[0];
				if (entry.getValue() != null)
					levelNameArr = ((String) entry.getValue()).split("@@");
				int i = 0;
				do {
					if (i >= 5)
						break;
					Object empDeptNo;
					try {
						empDeptNo = PropertyUtils.getProperty(emp,
								(new StringBuilder()).append("empDeptNo")
										.append(i + 1).toString());
						if (empDeptNo != null
								&& (i >= levelNameArr.length || !levelNameArr[i]
										.equals(((Department) empDeptNo)
												.getDepartmentName()))) {
							deptMatch = false;
							break;
						}
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (NoSuchMethodException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					i++;
				} while (true);
			} while (!deptMatch);
			emp.getEmpDeptNo().setId(deptIdName[0]);
		} while (++count < 2);
		if (!deptExist)
			return null;
		else
			return Integer.valueOf(count);
	}

	public Integer checkInputDeptLevel(Emptransfer transfer, String fieldName,
			Map levelNameMap) {
		int count;
		boolean deptExist;
		Iterator i$;
		count = 0;
		deptExist = false;
		i$ = levelNameMap.entrySet().iterator();
		do {
			boolean deptMatch;
			String deptIdName[] = null;
			Department dept = null;
			do {
				String levelNameArr[];
				Entry entry = null;
				do {
					if (!i$.hasNext())
						break; /* Loop/switch isn't completed */
					entry = (Entry) i$.next();
					deptIdName = ((String) entry.getKey()).split("@@");
					try {
						dept = (Department) PropertyUtils.getProperty(transfer,
								fieldName);
					} catch (Exception e) {
						e.printStackTrace();
						return null;
					}
				} while (!deptIdName[1].equals(dept.getDepartmentName()));
				deptExist = true;
				deptMatch = true;
				levelNameArr = new String[0];
				if (entry.getValue() != null)
					levelNameArr = ((String) entry.getValue()).split("@@");
				int i = 0;
				do {
					if (i >= 5)
						break;
					Object empDeptNo;
					try {
						empDeptNo = PropertyUtils.getProperty(transfer,
								(new StringBuilder()).append(fieldName).append(
										i + 1).toString());
						if (empDeptNo != null
								&& (i >= levelNameArr.length || !levelNameArr[i]
										.equals(((Department) empDeptNo)
												.getDepartmentName()))) {
							deptMatch = false;
							break;
						}
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (NoSuchMethodException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					i++;
				} while (true);
			} while (!deptMatch);

			dept.setId(deptIdName[0]);
		} while (++count < 2);
		if (!deptExist)
			return null;
		else
			return Integer.valueOf(count);
	}

	private Department getDeptById(List deptList, String deptId) {
		for (int i = 0; deptList != null && i < deptList.size(); i++) {
			Department dept = (Department) deptList.get(i);
			if (deptId != null && dept != null && deptId.equals(dept.getId()))
				return dept;
		}

		return null;
	}

	public boolean saveDeptOrder(String ids[]) {
		if (ids == null || ids.length == 0)
			return true;
		for (int i = 0; i < ids.length; i++) {
			int order = i + 1;
			String hql = (new StringBuilder()).append(
					"update Department set departmentSortId=").append(order)
					.append(" where id='").append(ids[i]).append("'")
					.toString();
			dao.exeHql(hql);
		}

		return true;
	}

	public IDepartmentDAO getDao() {
		return dao;
	}

	public void setDao(IDepartmentDAO dao) {
		this.dao = dao;
	}

	private IDepartmentDAO dao;
	private OrgDeptOperateHelper helper;
}
